package com.wzm.user.service.impl;

import com.wzm.basic.constant.VerifyCodeConstant;
import com.wzm.basic.exception.BusinessException;
import com.wzm.basic.util.Md5Utils;
import com.wzm.basic.util.StrUtils;
import com.wzm.user.domain.Logininfo;
import com.wzm.user.domain.User;
import com.wzm.user.domain.UserDto;
import com.wzm.user.mapper.LogininfoMapper;
import com.wzm.user.mapper.UserMapper;
import com.wzm.user.service.IUserService;
import com.wzm.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional
    public void add(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setPassword(md5Pwd);

        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        user.setLogininfoId(logininfo.getId());

        super.add(user);
    }

    @Override
    @Transactional
    public void del(Long id) {
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());
        super.del(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setPassword(md5Pwd);

        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfoId();
        //登录信息logininfo：type不修改
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);
        super.update(user);
    }

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String code = userDto.getCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();


        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("数据不能为空");
        }
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("两次密码不一致");
        }

        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstant.REGISTER_CODE_PREFIX + phone);
        if (obj == null) {
            throw new BusinessException("验证码过期");
        }
        String codeTmp = obj.toString().split(":")[0];
        if (!codeTmp.equals(code)) {
            throw new BusinessException("验证码错误");
        }

        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);

        user.setLogininfoId(logininfo.getId());

        userMapper.save(user);
    }

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("数据不能为空");
        }
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);

        user.setLogininfoId(logininfo.getId());

        userMapper.save(user);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        //发送方
        helper.setFrom("wzm75675@foxmail.com");
        //接收目标方
        helper.setTo(email);
        //邮件主题
        helper.setSubject("邮箱注册");
        //邮件内容
        helper.setText("<h2>邮箱账号注册<br>" +
                "<a href='http://localhost:8080/user/active/"+user.getId()+"'>点击此处注册激活</a></h2>",true);
        //发送邮件
        javaMailSender.send(mimeMessage);

    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        if(userDto.getEmail()!=null){
            user.setUsername(userDto.getEmail());
            user.setEmail(userDto.getEmail());
        }
        if(userDto.getPhone()!=null){
            user.setUsername(userDto.getPhone());
            user.setPhone(userDto.getPhone());
        }
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加盐加密
        String md5Pwd = Md5Utils.encrypByMd5( userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        return user;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

}
